import { AxiosResponse } from "axios";
import service from "@/api";
import { SYSTEM_CONFIG } from "@/config/system";
import { SERVICE_CONFIG } from "@/api/modules/_base";
import { JxtechSysConfig } from "@/stores/interface/sysconfig";
import { JxtechLoginUser, JxtechUser, UserDept } from "@/stores/interface/user";
import { JxtechToken } from "@/stores/interface/token";

/**登录接口 */
export function login(loginUser: JxtechLoginUser): Promise<AxiosResponse<JxtechToken>> {
  let url = SERVICE_CONFIG.ORG + "/oauth/token";
  const formData = new FormData();
  formData.set("client_id", SYSTEM_CONFIG.APP_ID);
  formData.set("client_secret", "password");
  formData.set("grant_type", "password");
  formData.set("password", loginUser.password as string);
  formData.set("username", loginUser.account as string);
  formData.set("locale", "zh-cn");
  return service.post(url, formData, {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  });
}

/**获取拾贝云用户信息 */
export function getUser(): Promise<AxiosResponse<JxtechUser>> {
  let url = SERVICE_CONFIG.ORG + "/user";
  return service.get(url);
}

/**获取系统配置信息 */
export function getSysConfig(): Promise<AxiosResponse<JxtechSysConfig>> {
  return service.post(SERVICE_CONFIG.ORG + "/getSysConfig", {
    appId: SYSTEM_CONFIG.APP_ID,
    appName: SYSTEM_CONFIG.APP_NAME,
    appDesc: SYSTEM_CONFIG.APP_NAME,
    appImage: "fa-group",
    loginType: "TOKEN",
    appBusComps: ["org"],
    clientSecret: "password",
    ssoProvider: "",
    appUrl: ""
  });
}

/**刷新token */
export function refreshToken(refreshToken: string): Promise<AxiosResponse<any>> {
  let url = SERVICE_CONFIG.ORG + "/oauth/token";
  const formData = new FormData();
  formData.set("client_id", SYSTEM_CONFIG.APP_ID);
  formData.set("client_secret", "password");
  formData.set("refresh_token", refreshToken);
  return service.post(url, formData, {
    params: {
      grant_type: "refresh_token"
    },
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  });
}

/**获取用户部门信息 */
export function getUserDept(): Promise<AxiosResponse<UserDept[]>> {
  return service.post(SERVICE_CONFIG.ORG + "/org/ManagerService/getAllDept", {});
}
